<script lang="tsx">
/**
 * tab栏
 */
export default {
  name: "tabs-form"
}
</script>

<script lang="tsx" setup>
import TabsFormManager from "@/framework/components/tabs-form/tabs-form-manager.ts"
import tabsFormManager from "@/framework/components/tabs-form/tabs-form-manager.ts"
import {ref, watch} from "vue"

/**
 * 定义props
 */
const propsData = defineProps<{
  tabsFormModel: TabsFormManager
}>()

/**
 * 定义emit
 */
const emit = defineEmits<{
  (e: 'tabsFormChange'): void
  (e: 'tabsFormClick', data: string): void
}>()

/**
 * tab栏组件
 */
const tabsFormModel = ref<tabsFormManager>()

/**
 * tab栏数据
 */
const tabsFormData = ref()

/**
 * 点击
 */
const handleClick = () => {
  emit('tabsFormClick', tabsFormData.value)
}

/**
 * 获取tab栏值
 */
const getTabsFormData = () => {
  return tabsFormModel.value?.els.find((item: any) => {
    return item.label === tabsFormData.value
  })
}

/**
 * 设置tabs栏值
 */
const setTabsFormData = (data: any) => {
  tabsFormData.value = data
}

/**
 * 初始化tabs模型
 */
const initPlugins = (newValue: any) => {
  tabsFormModel.value = newValue
  if (newValue.plugins) {
    newValue.plugins.forEach((plugin: any) => {
      plugin(tabsFormModel.value)
    })
  }
}

/**
 * 初始化数据
 */
const initData = () => {
  if (tabsFormModel.value?.initData) {
    setTabsFormData(tabsFormModel.value.initData)
  } else {
    setTabsFormData(tabsFormModel.value?.els[0].label)
  }
}

/**
 * 适配renderFn函数传参
 */
const computedRender = (item: any, data: any) => {
  return item.renderFn(data)
}

/**
 * 监视
 */
watch(() => propsData.tabsFormModel, (newValue: any) => {
  if (newValue) {
    initPlugins(newValue)
    initData()
  }
}, {
  deep: true,
  immediate: true
})

/**
 * 监视
 */
watch(() => tabsFormData.value, () => {
  emit("tabsFormChange")
})

/**
 * 暴露
 */
defineExpose({
  getTabsFormData,
  setTabsFormData
})
</script>

<template>
  <div class="tabs-form">
    <el-tabs v-model="tabsFormData" class="tabs-form-logout" @tab-click="handleClick">
      <el-tab-pane v-for="(item,index) in tabsFormModel?.els" :key="index" :label="item.label"
                   :name="item.label">
        <template v-if="tabsFormModel?.renderFn" #label>
          <component :is="computedRender(tabsFormModel,item)"/>
        </template>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<style lang="scss" scoped>

</style>